package com.zengqingfa.shardingjdbc.demo.sharding;

import com.google.common.collect.Lists;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Map;


public class BillShardingTableComplexAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<String> shardingValue) {
        Map<String, Collection<String>> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        if (columnNameAndShardingValuesMap.containsKey("tenant_code")) {
            Collection<String> tenant_code = columnNameAndShardingValuesMap.get("tenant_code");
            String tenantCode = String.valueOf(tenant_code.iterator().next());
            long tenant_code_mod = Math.abs(tenantCode.hashCode() / 2 % 3 + 1);
            for (String availableTargetName : availableTargetNames) {
                if (availableTargetName.endsWith(String.format("%02d", tenant_code_mod))) {
                    return Lists.newArrayList(availableTargetName);
                }
            }
        }
        throw new UnsupportedOperationException();
    }

}

